/*
 * @Author: szx
 * @Date: 2022-03-16 16:42:13
 * @LastEditTime: 2022-03-16 16:51:36
 * @Description:
 * @FilePath: \learn\手撸JS源码\map.js
 */
Array.prototype.myMap = function (callbackFn, thisArg) {
    // null 或 undefined
    if (this == null) {
        throw new TypeError(`can't not read proterty 'map' of ${this}`);
    }
    // 为啥不用typeof
    if (Object.prototype.toString.call(callbackFn) !== '[object Function]') {
        throw new TypeError(`${callbackFn} is not a function!`);
    }

    let obj = Object(this); // 规定 this 需要先转换为对象
    let len = obj.length >>> 0; // 保证 len 为数字且为整数
    // 这里为啥不是 thisArg|| this;
    let _this = thisArg || null;

    let res = new Array(len);

    for (let i = 0; i < len; ++i) {
        if (i in obj) {
            // 这一步对应数组中某些为empty的情况
            let mappedValue = callbackFn.call(_this, obj[i], i, obj);
            res[i] = mappedValue;
        }
    }
    return res;
};
